package com.tc.itfarm.commons.web.security;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.tc.itfarm.commons.web.security.model.CurUser;
import com.tc.itfarm.model.RolePrivilege;
import com.tc.itfarm.model.User;
import com.tc.itfarm.model.UserRole;
import com.tc.itfarm.service.RolePrivilegeService;
import com.tc.itfarm.service.RoleService;
import com.tc.itfarm.service.UserRoleService;
import com.tc.itfarm.service.UserService;

@SuppressWarnings("deprecation")
@Service("commonUserDetailService")
public class CommonUserDetailService implements UserDetailsService {

	private Logger logger = LoggerFactory.getLogger(CommonUserDetailService.class);
	@Resource
	private UserService userService;
	@Resource
	private RolePrivilegeService rolePrivilegeService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userService.selectByUsername(username);
		if (user == null) {
			logger.error("用户名不存在");
			throw new AccessDeniedException("用户名或密码不正确");
		}
		List<RolePrivilege> rolePrivilegeList = rolePrivilegeService.selectByUserId(user.getRecordId());
		List<GrantedAuthority> authorities = Lists.newArrayList();
		authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
		for (RolePrivilege rp : rolePrivilegeList) {
			authorities.add(new GrantedAuthorityImpl(rp.getPrivilegeCode()));
		}
		return new CurUser(username, user.getPassword(), true, true, true, true, authorities, user);
	}

}
